package com.neuedu.corejava.ch14.homework;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class Test {

	public static void work() {
		int port = 8888;
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;

		try {
			serverSocket = new ServerSocket(port);
			System.out.println("连接服务器成功");
			socket = serverSocket.accept();
			System.out.println("客户端连接成功");
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			String buffer = "Please enter a set of integers separated by a space(press 00 to end):";
			String exit = "Secure exit server";
			outputStream.write(buffer.getBytes());
			byte[] b = new byte[512];
			int x = 0;
			while (true) {

				int len = inputStream.read(b);
				String string = new String(b, 0, len).trim();
				// 排序
				String[] arr = string.split(" ");
				String string2="";
				try {
					int[]a=arrayAndSort(arr);
					string2=intoString(a, " ");
				} catch (Exception e) {
					string2="NumberFormatException";
				}
				System.out.println(string2);
				outputStream.write(("fwq:" + string2).getBytes());
				System.out.println();
				if ("00".equalsIgnoreCase(string)) {
					outputStream.write(exit.getBytes());
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeAll( socket, inputStream, outputStream);

		}

	}

	private static void closeAll( Socket socket, InputStream inputStream,
			OutputStream outputStream) {

		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					

				}
			}
		}
	}
	public static String intoString(int[] a,String flag) {
		
		StringBuffer string=new StringBuffer();
				
		for (int i : a) {
			string.append(i).append(flag);
		}
		return string.toString();
	}
	public static  int[] arrayAndSort(String[]strings) {
		int[] a = new int[strings.length];
		for(int i=0;i<a.length;i++) {
			a[i]=Integer.parseInt(strings[i]);
		}
		Arrays.sort(a);
		
		return a;
	}
	public static void main(String[] args) {
		work();
	}
}
